package com.lhkj.ct.framework.filter;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

/**
 * <p>
 *     对nginx转发后的项目名、端口、协议等进行匹配修复
 * </p>
 */
public class ParameterRequestWrapper extends HttpServletRequestWrapper {

    private final String oldContextPath;

    private final String oldRequestURI;

    private final String UNKNOWN = "unknown";

     ParameterRequestWrapper(HttpServletRequest request) {
         super(request);
         oldContextPath = request.getContextPath();
         oldRequestURI = request.getRequestURI();
    }

    @Override
    public String getContextPath() {
        //先从nginx自定义配置获取
        String contextPath = super.getContextPath();
        String temp = getHeader("Context-Path");
        if (StringUtils.isNotEmpty(temp) && ! UNKNOWN.equalsIgnoreCase(temp)) {
            contextPath = temp;
        }
        return contextPath;
    }

    @Override
    public String getRequestURI() {
         // 把requestURI 的 oldContextPath 部分替换成 新的 contextPath
        String requestURI = super.getRequestURI();
        if ( requestURI.startsWith(oldContextPath) ) {
            requestURI = getContextPath() + requestURI.substring(oldContextPath.length());
        }
        return requestURI;
    }

    @Override
    public StringBuffer getRequestURL() {
        // 把 RequestURL 的 oldRequestURI 部分替换成 新的 oldRequestURI
        StringBuffer requestURL = super.getRequestURL();
        String toString = requestURL.toString();
        if ( toString.endsWith(oldRequestURI) ) {
            requestURL.replace(
                    toString.indexOf(oldRequestURI), toString.indexOf(oldRequestURI) + oldRequestURI.length()
                    , getRequestURI());
        }
        return requestURL;
    }

    @Override
    public String getScheme() {
        //先从nginx自定义配置获取
        String scheme = super.getScheme();
        String temp = getHeader("X-Forwarded-Proto");
        if (StringUtils.isNotEmpty(temp) && ! UNKNOWN.equalsIgnoreCase(temp)) {
            scheme = temp;
        }
        return scheme;
    }

    @Override
    public int getServerPort() {
        //先从nginx自定义配置获取
        int serverPort = super.getServerPort();
        String temp = getHeader("Port");
        if (StringUtils.isNotEmpty(temp) && ! UNKNOWN.equalsIgnoreCase(temp)) {
            serverPort = Integer.parseInt(temp);
        }
        return serverPort;
    }



}
